const Base = require("./base.js");
const puppeteer = require("puppeteer");
module.exports = class extends Base {
  indexAction() {
    return this.display();
  }

  async detailAction() {
    let pageNum = 0;
    const doTask = async () => {
      const tasks = await this.model("puppeteer")
        .limit(pageNum, 1)
        .where({ status: 0 })
        .select();
      if (tasks.length > 0) {
        const task = tasks[0];
        const browser = await puppeteer.launch({
          headless: true
        });
        const page = await browser.newPage();
        await page.goto(task.url);
        const Handler = require("../../common/lib/puppeteer/HaodfJibingDetail");
        const handler = new Handler(page);
        let status = 0;
        try {
          await handler.pre();
          const data = await handler.evaluate();
          const form = {
            cate_name: task.cate,
            name: task.name,
            url: task.url,
            description: data.description,
            node_list: JSON.stringify(data.nodeList)
          };
          console.log(form);
          await handler.post(form);
          status = 1;
        } catch (e) {
          console.log(task.name + "采集失败");
          status = 2;
        }
        await this.model("puppeteer")
          .where({ id: task.id })
          .update({
            status
          });
        await browser.close();
        await doTask();
      }
    };
    await doTask();
  }
};
